#include('header.html')
<script type="text/javascript">
  // 改变侧边栏激活
  changeTab(1);
</script>
<style>
  .write-bottom {
    padding: 10px 20px 15px 0;
  }

  div[class='input-group'] label {
    color: #fff;
  }

  div#img {
    border: 2px dashed #2F8099;
    text-align: center;
    height: 120px;
    line-height: 120px;
    cursor: crosshair;
  }

  div#img > img {
    width: 100%;
    height: 98%;
  }

  /*发布中样式*/
  .loading {
    background-image: url(/static/images/loading.jpg);
    background-size: 16px 16px;
    background-position: 65px 48%;
    background-repeat: no-repeat;
    padding-right: 28px;
  }
</style>
<div class="admin-content">
  <div class="admin-box">
    <div class="col-lg-12 col-xs-12">
      <h4 class="pull-left">{{active}}</h4>
    </div>
    <div style="padding: 0;" class="col-lg-12 col-xs-12">
      <form>
        <div style="padding: 0 0 0 5px;" class="col-lg-9 col-xs-9">
          <div class="col-lg-8 col-xs-8">
            <div class="form-group">
              <div class="input-group">
                <label style="background-color: #792F5C;" class="input-group-addon">标题</label>
                <input class="form-control" placeholder="文章标题 (必须)" v-model="article.title">
              </div>
              <span class="text-danger"></span>
            </div>
          </div>
          <div class="col-lg-4 col-xs-4">
            <div class="form-group">
              <div class="input-group">
                <select class="form-control" v-model="article.type">
                  <option v-for="(v, k) in types" :value="k">{{v}}</option>
                </select>
                <label style="background-color: #64298B;" class="input-group-addon bg-info">分类</label>
              </div>
            </div>
          </div>
          <div class="col-lg-12 col-xs-12">
            <div class="form-group">
              <div class="input-group">
                <label style="background-color: #316b9d;" class="input-group-addon">简介</label>
                <textarea class="form-control" rows="3" style="resize: none;" maxlength="150"
                          placeholder="文章简介150字内" v-model="article.intro"></textarea>
              </div>
              <span class="text-danger"></span>
            </div>
          </div>
        </div>

        <div style="padding: 0 25px 0 0;" class="col-lg-3 col-xs-3">
          <div id="img" @click="upImg">
            <img v-show="article.photo !== '' && article.photo !== null" :src="article.photo">
            <span v-show="(article.photo === '' || article.photo == null) && article.type === 'result'">添加缩略图</span>
            <span v-show="(article.photo === '' || article.photo == null) && article.type !== 'result'">无缩略图</span>
          </div>
        </div>
      </form>
    </div>

    <div class="col-lg-12 col-xs-12">
      <span class="text-danger"></span>
      <div id="editor"></div>
    </div>

    <div class="col-lg-12 col-xs-12 write-bottom">
      <div class="text-right">
        <a href="/admin/articles" class="btn btn-default">返回列表</a>
        <button v-show="!saving" @click="saveOrUpdate(0)"
                class="btn btn-warning">保存草稿
        </button>
        <span v-show="saving" class="btn btn-warning loading">保存中..</span>
        <button v-show="!publishing" @click="saveOrUpdate(1)"
                class="btn btn-success">发布文章
        </button>
        <span v-show="publishing" class="btn btn-success loading">发布中..</span>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript" src="https://cdn.bootcss.com/wangEditor/3.1.1/wangEditor.min.js"></script>
<script type="text/javascript" src="/static/style/weditor/we-full.js"></script>
<link rel="stylesheet" href="/static/style/weditor/we-full.css">
<script type="text/javascript">
  function clearArt(object) {
    for (var key in object) {
      switch (key) {
        case 'type':
          object[key] = 'news';
          break;
        case 'photo':
          object[key] = '';
          break;
        default:
          object[key] = null;
      }
    }
  }

  function isEmpty(text) {
    return text === undefined || text === null || text === '';
  }

  var editor = null;
  var pbs = new Vue({
    el: '.admin-box',
    data: {
      active: ${id ? '"修改文章"':'"发布文章"'},
      article: {
        id: ${id ?! 'null'},
        type: "news",
        status: 0,
        photo: "",
        flagKey: ""
      },
      tempPhoto: "", // 用来临时保存图片路径
      types: {
        news: '创客动态',
        notice: '通知公告',
        result: '成果展示'
      },
      saving: false,
      publishing: false
    },
    methods: {
      upImg: function () {
        if (this.article.type === 'result') {
          var input = document.createElement('input');
          input.setAttribute('type', 'file');
          input.setAttribute('accept', 'image/*');
          input.click();
          input.onchange = function () {
            imgZip(this.files[0], function (blob) {
              var fd = new FormData();
              fd.append('file', blob, "blob.jpeg");
              fd.append('type', 'result');

              var xhr = new XMLHttpRequest();
              xhr.open('post', '/file/upload', true);
              xhr.onload= function () {
                var data = JSON.parse(xhr.responseText);
                if (data.success) {
                  pbs.article.photo = data.payload.url;
                } else {
                  console.log("图片上传失败！" + data);
                }
              };
              xhr.send(fd);
            });
          }
        }
      },
      saveOrUpdate: function (status) {
        if (editor !== null) {
          var html = editor.txt.html();
          var text = editor.txt.text();
          if (text !== '') {
            this.article.content = html;
          }
          this.article.status = status;

          var url = [true, '/article/add'];
          if (this.article.id !== null && this.article.id > 0) {
            url[0] = false;
            url[1] = '/article/change';
          }
          if (this.checkForm()) {
            if (status === 0)
              this.saving = true;
            else
              this.publishing = true;
            $.post(url[1], this.article, function (data) {
              if (data.success) {
                if (url[0]) { // 再添加的时候会自动清空
                  editor.txt.clear();
                  clearArt(pbs.article);
                } else {
                  pbs.article.path = data.payload.path;
                }
                alert((status === 0 ? '保存' : '发布') + "成功！");
              } else {
                console.log("保存失败！");
                alert("ERROR: " + data.msg);
              }
              pbs.saving = false;
              pbs.publishing = false;
            });
          }
          this.tempPhoto = '';
        }
      },
      checkForm: function () {
        if (isEmpty(this.article.title) && isEmpty(this.article.intro) && isEmpty(this.article.content))
          return false;
        var msg = "";
        if (this.article.title === null || this.article.title.length < 4) {
          msg = "标题太短！";
        } else if (this.article.intro === null || this.article.intro.length < 10) {
          msg = "简介太少！";
        } else if (this.article.content === null || this.article.content.length < 16) {
          msg = "文章内容太少了！";
        } else {
          return true;
        }
        alert("WARN: " + msg);
        return false;
      }
    },
    watch: {
      'article.type': function (nv, ov) {
        if (nv !== 'result' && (this.article.photo !== '' || this.article.photo !== null)) {
          this.tempPhoto = this.article.photo;
          this.article.photo = '';
        } else if (nv === 'result' && this.tempPhoto !== '') {
          this.article.photo = this.tempPhoto;
        }
      }
    },
    mounted: function () {
      var self = this;
      if (this.article.id > 0) {
        $.post('/article/one/' + this.article.id, function (data) {
          if (data.success) {
            self.article = data.payload;
            $.get(self.article.path, function (html) {
              html = html.replace("<meta charset='utf-8'>", ''); // 必须过滤掉 不然会一直重复
              editor.txt.html(html);
            });
          } else {
            console.log("获取文章失败！" + data);
          }
        });
      } else {
        this.article.flagKey = parseInt(Math.random() * 10000) + "" + new Date().getTime();
      }
    }
  });

  editor = new window.wangEditor('#editor');
  editor.customConfig.uploadFileName = 'file';
  // editor.customConfig.uploadImgServer = '/file/wangUpload';
  // editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024;  // 限制图片大小为2兆
  // editor.customConfig.uploadImgParams = {
  //   key: pbs.article.flagKey
  // };
  editor.customConfig.customUploadImg = function (files, insert) {
    imgZip(files[0], function (blob) {
      var fd = new FormData();
      fd.append("file", blob, "img.jpeg");
      fd.append("key", pbs.article.flagKey);
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "/file/wangUpload", true);
      xhr.onload = function () {
        var data = JSON.parse(xhr.responseText);
        if (data.success) {
            insert(data.payload);
        } else {
          console.log("上传文件失败！-" + xhr.responseText)
        }
      };
      xhr.send(fd);
    });
  };
  editor.create(); // 创建
  fullscreen.init('#editor'); // 全屏
</script>
#include("footer.html")
                                                                                             